package com.fun_ordering.filter;

import com.fun_ordering.entity.LoginUser;
import com.fun_ordering.pojo.FoEmployee;
import com.fun_ordering.util.JJwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;



@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String usertoken = request.getHeader("Token");
        if (!StringUtils.hasText(usertoken)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //解析用户给的token  有可能是非法token  如果是非法 进行异常处理
        String empAccount = null;
        try {
            FoEmployee foEmployee = JJwtUtil.decode(usertoken);
            empAccount = foEmployee.getEmpAccount();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //从redis中获取用户信息stringRedisTemplate.opsForValue().set("login:user:"+foEmployee.getEmpAccount(),token);
        String redisToken = stringRedisTemplate.opsForValue().get("login:user:" + empAccount);
        if(StringUtils.isEmpty(redisToken)){
            throw new RuntimeException("用户未登录");
        }
        //用户登录过的user信息  解析token
        FoEmployee redisEmp = JJwtUtil.decode(redisToken);
        //传入security中
        LoginUser user = new LoginUser(redisEmp);

        //封装Authentication对象存入SecurityContextHolder
        //TODO 获取权限信息封装到Authentication中
        
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user,null,null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }
}
